package com.rowline.admin.module.study.dynamicproxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * ClassName:MyAspect
 * Created by 245167
 * on 2018/1/18  18:41
 * description:
 */
public class MyAspect {

    @Pointcut(value = "execution(com.rowline.admin.module.study.*)")
    private void myPointcut(){
    }

    @Before("myPointCut()")
    public void myBefore(JoinPoint joinPoint) {
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }

    @Before("myPointCut()")
    public void myAfterReturning(JoinPoint joinPoint, Object ret) {
        System.out.println("后置通知 : " + ret);
    }

    @Before("myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("前");
        // 手动执行目标类
        Object obj = joinPoint.proceed();

        System.out.println("后");
        return obj;
    }

//    public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
//        System.out.println("抛出异常 : " + e.getMessage());
//    }

    //该表达式指定com/annotation目录下及其所有子目录下的所有带有@MyLog注解的方法体为切点。
    @After("myPointCut()")
    public void myAfter(JoinPoint joinPoint,MyLog log) throws NoSuchMethodException,
            SecurityException {
      printLog(joinPoint,log);
    }

    private void printLog(JoinPoint joinPoint,MyLog log) throws NoSuchMethodException,
            SecurityException {
        Class targetClass = joinPoint.getTarget().getClass();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();

        Class[] parameterTypes = null;

        if (arguments != null) {
            int length = arguments.length;
            parameterTypes = new Class[length];

            for (int i = 0; i < length; ++i) {
                parameterTypes[i] = arguments[i].getClass();
            }
        }

//        MyLog log = null;
//        Method method = targetClass.getMethod(methodName, parameterTypes);
//        if (method != null) {
//            log = method.getAnnotation(MyLog.class);
//        }
//        if (log != null) {
//            System.out.println("====log======" + log.value());
//            if(log.value()==110){
//                System.out.println("日志注解中的值是110");
//            }
//            saveLog(log);
//        }
    }

    private void saveLog(MyLog log) {
        System.out.println("插入日志记录");
        System.out.println();
    }
}
